package cn.lyjuan.pojoutils.util;

import java.io.File;
import java.io.PrintWriter;
import java.net.URLDecoder;

/**
 * Created by ly on 2014/11/23.
 */
public class FileUtils
{
    /**
     * 生成 JAVA 文件
     * @param pkg
     *                  JAVA 文件包
     * @param clazz
     *                  JAVA 文件名
     * @param content
     *                  JAVA 文件内容
     */
    public static void saveClass(String pkg, String clazz, String content, String src) throws Exception
    {
        String filePath = FileUtils.class.getClassLoader().getResource("").getPath();

        if (filePath.indexOf("WebRoot/WEB-INF/classes") > -1)
            filePath = filePath.substring(0, filePath.lastIndexOf("WebRoot/WEB-INF/classes/")) + src + "/";
        else
        {
            filePath = filePath.substring(0, filePath.indexOf("/out/") + 1) + src +  "/";
//            filePath = filePath.substring(0, filePath.length() - 4) + src + "/";
        }

        pkg = pkg.replaceAll("\\.", "/");

        filePath = filePath + pkg + "/" + clazz;

        filePath = URLDecoder.decode(filePath, "UTF-8");

        System.out.println("saveClass >> " + filePath);

        File f = new File(filePath);

        if (!f.getParentFile().isDirectory())
            f.getParentFile().mkdirs();

        PrintWriter out = new PrintWriter(f);

        out.write(content);
        out.flush();
        out.close();
    }
}
